package com.webchat.netty.gateway.listener;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.AbstractEventListener;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.webchat.common.constants.NettySocketConstants;
import com.webchat.netty.gateway.config.properties.NacosConfig;
import com.webchat.netty.gateway.router.RouterTable;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Slf4j
public class NacosEventListener {


    private static NamingService namingService;
    private static RouterTable routerTable;

    ExecutorService executorService = Executors.newFixedThreadPool(1);


    public static void init(NacosConfig nacosConfig) {
        try {
            routerTable = new RouterTable();
            Properties properties = new Properties();
            properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosConfig.getServerAddr());
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosConfig.getNamespace());
            namingService = NacosFactory.createNamingService(properties);
        } catch (NacosException e) {
            log.error("nacos server connect error. ", e);
        }
    }

    /**
     * 开启监听
     *
     */
    public void start() {
        try {
            namingService.subscribe(NettySocketConstants.SERVICE_NAME, listener());
        } catch (NacosException e) {
            log.error("nacos server listener start error. ", e);
            throw new RuntimeException(e);
        }
    }

    private EventListener listener() {

        return new AbstractEventListener() {
            @Override
            public void onEvent(Event event) {
                if (event instanceof NamingEvent) {
                    List<Instance> instances = ((NamingEvent) event).getInstances();
                    routerTable.doUpdate(instances);
                }
            }
            @Override
            public Executor getExecutor() {
                return executorService;
            }
        };
    }
}
